package com.cntcdt.api.db.mongodb;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.bson.Document;

import com.cntcdt.api.db.model.ShopModel;
import com.cntcdt.api.utils.ConfigReadUtils;
import com.cntcdt.api.utils.LogUtils;
import com.mongodb.BasicDBObject;
import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoDatabase;

/**
 * 查询附近的列表
 * @author luochangming
 *
 */
public class NearSearch {
	public static MongoDatabase db = null;
	static{
		String mongodb_address = ConfigReadUtils.loadConfigByConfDir("qinqinconfig.properties").getProperty("mongodb_address");
		String mongodb_port = ConfigReadUtils.loadConfigByConfDir("qinqinconfig.properties").getProperty("mongodb_port");
		MongoClient mongoClient = new MongoClient(mongodb_address, Integer.valueOf(mongodb_port));
		db = mongoClient.getDatabase("cdt");
	}
	
	
	/**
	 * 根据经纬度查询附近的商店
	 * @param lng 经度
	 * @param lat 纬度
	 * @param limit 查询的条数
	 * @param pageNo 查询的页码 第一页为1
	 */
	public static  List<Integer> queryNear(double lng , double lat , int limit  , int pageNo){
		final List<Integer> result = new ArrayList<Integer>();
		
		double lat_lng_values[] = {lng, lat};
		
		BasicDBObject geo = new BasicDBObject("$geometry", new BasicDBObject("type","Point").append("coordinates",lat_lng_values));
//		geo.append("$maxDistance", 1000);
	    BasicDBObject filter = new BasicDBObject("$nearSphere", geo);
	    BasicDBObject locQuery = new BasicDBObject("coord", filter);
//	    LogUtils.log.info(locQuery);
		
	    FindIterable<Document> iterable = db.getCollection("cdt_shop").find(locQuery).limit(limit).skip((pageNo-1)*limit);
	    iterable.forEach(new Block<Document>() {
		    public void apply(final Document document) {
		        LogUtils.log.info(document.toString());
		        result.add(document.getInteger("shopId"));
		    }
		});
		
//		mongoClient.close();
	    return result;
	}
	
	/**
	 *更新商店信息
	 * @param shop
	 * @return
	 */
	public static boolean updateShop(ShopModel shop){
		boolean result = false;
		
		return result;
	}
	
	/**
	 * 查找附近的人和商店
	 * @param lng
	 * @param lat
	 * @param limit
	 * @param pageNo
	 * @return
	 */
	public static List<Map<String,Integer>> queryNear2(double lng , double lat , int limit  , int pageNo,int userId){
		final List<Map<String,Integer>> result = new ArrayList<Map<String,Integer>>();
		
		double lat_lng_values[] = {lng, lat};
		
		BasicDBObject geo = new BasicDBObject("$geometry", new BasicDBObject("type","Point").append("coordinates",lat_lng_values));
		
	    BasicDBObject filter = new BasicDBObject("$nearSphere", geo);
	    
//	    List<BasicDBObject> orList = new ArrayList<BasicDBObject>();
//	    BasicDBObject orFilter1 = new BasicDBObject("isBorrow", 1);
//	    BasicDBObject orFilter2 = new BasicDBObject("type", "2");
//	    orList.add(orFilter1);
//	    orList.add(orFilter2);
//	    .append("userId", new BasicDBObject("$ne",userId))
//	    BasicDBObject locQuery = new BasicDBObject("coord", filter).append("$or", orList).append("isOpen", 1).append("version",new BasicDBObject("$gt",250));
	    BasicDBObject locQuery = new BasicDBObject("coord", filter).append("type", "2");
//	    locQuery.put("coord", new BasicDBObject("$ne",asList(0,0)));
	    LogUtils.log.info(locQuery.toString());
		
	    FindIterable<Document> iterable = db.getCollection("cdt_nearby_user_shop").find(locQuery).limit(limit).skip((pageNo-1)*limit);
	    iterable.forEach(new Block<Document>() {
		    public void apply(final Document document) {
		        LogUtils.log.info(document.toString());
		        Map<String,Integer> idMap = new HashMap<String,Integer>();
		        idMap.put("userId", document.getInteger("userId"));
		        idMap.put("shopId", document.getInteger("shopId"));
		        result.add(idMap);
		    }
	    });
	    return result;
	}
	
	/**
	 * 查询附近的人
	 * @param lng
	 * @param lat
	 * @param limit
	 * @param pageNo
	 * @return
	 */
	public static List<Integer> queryNearbyPerson(double lng , double lat , int limit  , int pageNo,int userId){
		final List<Integer> result = new ArrayList<Integer>();
		
		double lat_lng_values[] = {lng, lat};
		
		BasicDBObject geo = new BasicDBObject("$geometry", new BasicDBObject("type","Point").append("coordinates",lat_lng_values)).append("$minDistance", 0).append("$maxDistance", 20000);
		
	    BasicDBObject filter = new BasicDBObject("$nearSphere", geo);
	    
	    List<BasicDBObject> orList = new ArrayList<BasicDBObject>();
	    BasicDBObject orFilter2 = new BasicDBObject("type", "1");
	    orList.add(orFilter2);
//	    .append("userId", new BasicDBObject("$ne",userId))
	    BasicDBObject locQuery = new BasicDBObject("coord", filter).append("$or", orList).append("isOpen", 1).append("isCoord", 1).append("version",new BasicDBObject("$gt",250));;
	    LogUtils.log.info(locQuery.toString());
		
	    FindIterable<Document> iterable = db.getCollection("cdt_nearby_user_shop").find(locQuery).limit(limit).skip((pageNo-1)*limit);
	    iterable.forEach(new Block<Document>() {
		    public void apply(final Document document) {
		        LogUtils.log.info(document.toString());
		        Map<String,Integer> idMap = new HashMap<String,Integer>();
		        result.add(document.getInteger("userId"));
		    }
	    });
	    return result;
	}
	
	/**
	 * 根据用户Id查询用户
	 * @param userId
	 * @return
	 */
	public static Integer queryByUserId(int userId){
		 final List<Integer> result = new ArrayList<Integer>();
	    BasicDBObject locQuery = new BasicDBObject("userId",userId);;
	    LogUtils.log.info(locQuery.toString());
		
	    FindIterable<Document> iterable = db.getCollection("cdt_nearby_user_shop").find(locQuery);
	    iterable.forEach(new Block<Document>() {
		    public void apply(final Document document) {
		        LogUtils.log.info(document.toString());
		        result.add(document.getInteger("isOpen"));
		    }
	    });
	    return result.get(0);
	}	
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		queryNearbyPerson(113.943617, 22.537976, 5, 1,1000002302);
		queryByUserId(1000027667);
//		LogUtils.log.info(result);
	}

}
